import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
var car = JSON.parse(localStorage.getItem("car") || "[]");
const store = new Vuex.Store({
  state: {
    car: car
  },
  mutations: {
    addToCar(state, goodsinfo) {
      var flag = false;
      state.car.some(item => {
        if (item.id == goodsinfo.id) {
          item.count += parseInt(goodsinfo.count);
          flag = true;
          return true;
        }
      });
      if (!flag) {
        state.car.push(goodsinfo);
      }
      // 当修改完商品的数量，把最新的购物车数据，保存到 本地存储中
      localStorage.setItem("car", JSON.stringify(state.car));
    }
  },
  getters: {
    getAllCount(state) {
      var c = 0;
      state.car.forEach(item => {
        c += item.count;
      });
      return c;
    }
  },
  actions: {},
  modules: {}
});
export default store;
